const kuaiApi = require("../api/kuai");
const { sleep } = require("./common");
const { useAgent } = require("./useAgent");

// 快手可灵
async function useKuaiDraw({ data, cookie }) {
  try {
    const agent = useAgent();
    const subRes = await kuaiApi.submit({ data, cookie, agent });
    // console.log(subRes);
    if (subRes.result == 1) {
      const { id } = subRes.data.task;
      var res;
      var count = 0;
      while (true) {
        if (count > 99) {
          return { code: 500, data: [], message: "fail" };
        }
        await sleep(5000);
        res = await kuaiApi.status({
          cookie,
          params: {
            taskId: id,
          },
        });
        // console.log(res,"...res");
        // console.log(res.data.works,"...res.data.works");
        if (res.data.status >= 95) {
          break;
        }
        if (res.data.status == 50) {
          break;
        }
        count++;
      }

      // console.log(res.data,"...res.data");

      return {
        code: 200,
        data: res.data.works
          .map((item) => item.resource.resource)
          .filter(Boolean),
        message: "success",
      };
    }
    return { code: 500, data: [], message: "fail" };
  } catch (error) {
    return { code: 500, data: [], message: error.message };
  }
}
module.exports = useKuaiDraw;
